[Vue 學習筆記(二)] Vue class 和 style binding


Posted by Powerfultraveling 's Blog on 2021-12-15

前言

vue 的 class binding 很特別,可以使用幾乎任何 JavaScript 的 expression 來做到,陣列、物件、條件式都可以,雖然易懂,但是 syntax 比較雜亂,所以在這邊記錄一下怎麼使用。

有甚麼特別?

一個個講太麻煩了,直接貼上程式碼,提點一下特別的點來複習吧:

  1. v-bind:class="" 那個 "" 裡面可以寫任何 JavaScript 的 expression。
  2. 可以用物件來寫條件式。
  3. 可以用陣列。
  4. inline-style 需要用駝峰式寫法。
<template>
  <div id="app">
    <h1 v-bind:class="isError ? 'error':'success'">{{msg}}</h1>
    <h1 v-bind:class="[isError ? 'error':'success', 'underline']">konichiwa</h1>
    <h1 v-bind:class="{
      error: isError,
      success: !isError
    }">object binding</h1>
    <h1 v-bind:style="[stlyeObj, stlyeObj2]">style</h1>
  </div>
</template>

<script>


export default {
  name: 'App',
  data(){
    return{
      msg: "hallo world",
      msg2: `<a href="#" onClick="alert("hallo")">hallo World</a>`,
      isDisabled: true,
      isError: false,
      stlyeObj:{
        color: "orange",
        fontSize: "52px",
        textDecoration: "underline"
      },
      stlyeObj2:{
        marginTop: "100px"
      }
    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.error{
  color: red
}

.success{
  color: green
}

.underline{
  text-decoration: underline;
}
</style>









Related Posts

Git 版本控制入門(4)- git 狀況劇

Git 版本控制入門(4)- git 狀況劇

關於 React 小書:評論功能

關於 React 小書:評論功能

在單一元件檔(.vue)裡面使用 Teleport

在單一元件檔(.vue)裡面使用 Teleport


Comments